﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.DBManager;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Services;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using syio = System.IO;
/// <summary>
/// 自定义api调用
/// </summary>
namespace VOL.WebApi.Controllers.MyTable.customer_api
{
    [Route("api/customer")]
    [ApiController]
    public class customer_weixin : Controller
    {
        private string appid_str = "wx7897cb67b0a0b45e";
        private string secret_str = "d24377ec3e6c178cf8d1b9523998591b";
      /*  private string yj_tempid = "OalDL1h6gMJsTgi3XLsmHSS1IYuEdalipUEgGHWvpCU";//预警模版id
        private string yj_temp_str = "{\"touser\": \"@openid@\"," +
                       "\"template_id\": \"@tempid@\", " +
                       "\"url\": \"@url@\", " +
                       "\"topcolor\": \"#FF0000\", " +
                       "\"data\": " +
                       "{\"first\": {\"value\": \"\"}," +
                       "\"keyword1\": { \"value\": \"@keyword1@\"}," +//预警内容
                       "\"keyword2\": { \"value\": \"@keyword2@\"}," + //预警时间
                       "\"remark\": {\"value\": \"@remark@\" }}}";

        private string dcl_tempid = "ewJUGX0Eu0W0esSShZyCleLB1gdTNiXmikXnDODErcE";//预警模版id
        private string dcl_temp_str = "{\"touser\": \"@openid@\"," +
                       "\"template_id\": \"@tempid@\", " +
                       "\"url\": \"@url@\", " +
                       "\"topcolor\": \"#FF0000\", " +
                       "\"data\": " +
                       "{\"first\": {\"value\": \"\"}," +
                       "\"keyword1\": { \"value\": \"@keyword1@\"}," +//工单编号
                       "\"keyword2\": { \"value\": \"@keyword2@\"}," + //工单标题
                       "\"keyword3\": { \"value\": \"@keyword3@\"}," +//发起人
                       "\"keyword4\": { \"value\": \"@keyword4@\"}," + //工单状态，待处理
                       "\"keyword5\": { \"value\": \"@keyword5@\"}," + //开始时间
                       "\"remark\": {\"value\": \"@remark@\" }}}";*/
        /// <summary>
        /// 获取用户openid,后实现系统自动登录
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("get_openid"), AllowAnonymous]
        public async Task<WebResponseContent> get_openid(string code)
        {
            string urL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid_str + "&secret=" + secret_str + "&code=" + code + "&grant_type=authorization_code";//用于获取openid
            WebResponseContent _webResponse = new WebResponseContent();
            string openid = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urL);
                request.Method = "GET";
                request.ContentType = "textml;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                syio.Stream myResponseStream = response.GetResponseStream();
                syio.StreamReader myStreamReader = new syio.StreamReader(myResponseStream, Encoding.UTF8);
                string jsonData = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                string jsonString = jsonData;
                JObject json = JObject.Parse(jsonString);
                openid = json["openid"].ToString();
                //Logger.Info(openid);
                //Console.WriteLine(openid);
                List<Wxgzh_login_map> _list_wx = await DBServerProvider.DbContext.Set<Wxgzh_login_map>().Where(w => w.openid == openid).ToListAsync();//跟函数返回值一致async
                                                                                                                                                      //Console.WriteLine(_list_wx.Count);
                                                                                                                                                      // Wxgzh_login_map _list_wx = await DBServerProvider.DbContext.Set<Wxgzh_login_map>().Where(w => w.openid == openid).FirstOrDefault();
                if (_list_wx.Count > 0)//之前登录过自动登录
                {
                    string token = "";
                    Sys_User user = null;
                    using (var db = DBServerProvider.DbContext)//自动登录
                    {
                        user = db.Set<Sys_User>().Where(x => x.UserName == _list_wx[0].uname).FirstOrDefault();
                        token = JwtHelper.IssueJwt(new UserInfo()
                        {
                            User_Id = user.User_Id,
                            UserName = user.UserName,
                            Role_Id = user.Role_Id
                        });
                        user.Token = token;
                        db.Update(user);
                        db.SaveChanges();
                    }
                    UserContext.Current.LogOut(user.User_Id);//这步不能少，表示客户端登录成功,否则token就超时。
                    // _webResponse.Code = "2";//系统自动登录，并转入到Home页,_webResponse.Code不能手工赋值，平台自动赋值
                    _webResponse.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl, wxopenid = openid };
                    //loginInfo.Password = string.Empty;
                    //Logger.Info("status==true,真实姓名：" + user.UserTrueName);

                    string openidstr = "oGHE6wnHTISjdy2vTW4XO41OvEU4";//提醒给hxs
                    string str = weixin_tools.yj_temp_str;//公众号发送提醒信息
                    str = str.Replace("@openid@", openidstr);
                    str = str.Replace("@url@", "http://ksh1.ctruck.com.cn");
                    str = str.Replace("@keyword1@", "公众号登录预警");
                    str = str.Replace("@keyword2@", DateTime.Now.ToString());
                    str = str.Replace("@remark@", "当前登录人："+user.UserTrueName);
                    weixin_tools.SendTempletMessge(str);

                    /*//提醒模版
                    openidstr = "oGHE6wnHTISjdy2vTW4XO41OvEU4";//提醒给hxs
                    string str1 = weixin_tools.dcl_temp_str;//使用的时候需要只提供消息字符串模版
                    str1 = str1.Replace("@openid@", openidstr);
                    str1 = str1.Replace("@url@", "http://ksh1.ctruck.com.cn");
                    str1 = str1.Replace("@keyword1@", "业务编号:XX");
                    str1 = str1.Replace("@keyword2@", "报销审批提醒");
                    str1 = str1.Replace("@keyword3@", user.UserTrueName);
                    str1 = str1.Replace("@keyword4@","待处理状态");
                    str1 = str1.Replace("@keyword5@", DateTime.Now.ToString());
                    str1 = str1.Replace("@remark@", "");
                    weixin_tools.SendTempletMessge(str1);*/

                    return _webResponse.OK(ResponseType.LoginSuccess);
                }
                else//没有登录过就转为手工登录。
                {
                    //Logger.Info("code=1");
                    _webResponse.Data = new { wxopenid = openid };
                    return _webResponse.Error("第一次登录，转到登录页，需要输入用户名和密码");
                }
                //return Json(_webResponse.OK("获取openid成功", openid));

            }
            catch (Exception e)
            {
                Logger.Info("发生异常" + e.Message.ToString());
                //Console.WriteLine("获取失败");
                return _webResponse.Error("获取失败,转到登录页" + e.Message.ToString());
            }

            //return rtn_hst;
        }

        
    }

   /* public class WXApi
    {
        public string access_token { set; get; }
    }*/
}
